import { ref } from 'vue';
import { getAudioBase64ById, getAudioFileById } from '@/api/translate';
import { toast } from '@/assets/js/utils';

export function usePlayAudio() {
    //当前播放的语音id
    const currentPlayId = ref('');
    //播放类型来源，1列表播放；2翻译框内播放
    const currentPlayType = ref(1);
    //播放音频
    let audio: any;

    const playAudio = async (id: any, type: number = 1) => {
        if (currentPlayId.value == id && currentPlayType.value == type && audio) {
            audio.stop();
        }
        currentPlayId.value = id;
        currentPlayType.value = type;
        let [result, err] = await getAudioBase64ById(id);
        // let [result, err] = await getAudioFileById(id);
        if (result) {
            let tempFilePath = await base64ToTempFile(`data:audio/wav;base64,${result}`);
            if (audio) {
                audio.stop();
            }
            audio = uni.createInnerAudioContext();
            audio.src = tempFilePath;
            audio.volume = 1;
            // #ifndef APP
            audio.obeyMuteSwitch = false;
            // #endif
            audio.play();
            //音频可以播放
            audio.onCanplay((res: any) => {
                console.log('可以开始播放');
            });
            //音频播放
            audio.onPlay((res: any) => {
                console.log('播放成功');
            });
            //音频等待播放
            audio.onWaiting((res: any) => {
                console.log('音频等待播放');
            });
            //播放错误
            audio.onError((res: any) => {
                currentPlayId.value = '';
                currentPlayType.value = 1;
                toast('播放失败，请稍后再试');
                console.log('播放错误', JSON.stringify(res));
            });
            //自然播放结束
            audio.onEnded((res: any) => {
                currentPlayId.value = '';
                currentPlayType.value = 1;
                console.log('自然播放结束', JSON.stringify(res));
            });
        }
    };

    return { currentPlayId, currentPlayType, playAudio };
}

// Base64转临时文件路径（全平台兼容）
const base64ToTempFile = (base64Data: any) => {
    return new Promise((resolve, reject) => {
        // #ifdef H5
        resolve(base64Data);// H5 直接使用 Data URL
        // #endif

        // #ifdef MP-WEIXIN
        // 小程序转为文件路径
        const [, format, data] = base64Data.match(/data:audio\/(\w+);base64,(.*)/);
        const fileManager = uni.getFileSystemManager();
        const fileName = `${Date.now()}.${format}`;
        fileManager.writeFile({
            filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
            data: data,
            encoding: 'base64',
            success: res => resolve(`${wx.env.USER_DATA_PATH}/${fileName}`),
            fail: reject
        });
        // #endif

        // #ifdef APP
        const [, format2, base64Data2] = base64Data.match(/data:audio\/(\w+);base64,(.*)/);
        plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs: any) {
            fs.root.getFile((new Date()).valueOf() + '.wav', {
                create: true
            }, function(entry: any) {
                var fullPath = entry.fullPath;
                let platform = uni.getSystemInfoSync().platform
                if (platform == 'android') {
                    var Base64: any = plus.android.importClass("android.util.Base64");
                    var FileOutputStream: any = plus.android.importClass("java.io.FileOutputStream");
                    try {
                        var out = new FileOutputStream(fullPath);
                        var bytes = Base64.decode(base64Data2, Base64.DEFAULT);
                        out.write(bytes);
                        out.close();
                        resolve(entry.toLocalURL())
                    } catch (e: any) {
                        console.log(e.message);
                    }
                } else if (platform == 'ios') {
                    // var NSData = plus.ios.importClass('NSData');
                    // var nsData = new NSData();
                    // nsData = nsData.initWithBase64EncodedStringoptions(base64Data2, 0);
                    // if (nsData) {
                    //     nsData.plusCallMethod({
                    //         writeToFile: fullPath,
                    //         atomically: true
                    //     });
                    //     plus.ios.deleteObject(nsData);
                    // }
                    // console.log(entry.toLocalURL());
                    
                }
            })
        })
        // #endif
    });
};
